package com.netdisk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.netdisk.dto.FileDTO;
import com.netdisk.entity.Favorite;
import com.netdisk.entity.File;
import com.netdisk.exception.BusinessException;
import com.netdisk.mapper.FavoriteMapper;
import com.netdisk.service.FavoriteService;
import com.netdisk.service.FileService;
import com.netdisk.vo.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏服务实现类
 */
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {

    @Autowired
    private FileService fileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addFavorite(Integer fileId, Integer userId) {
        // 检查文件是否存在
        LambdaQueryWrapper<File> fileQueryWrapper = new LambdaQueryWrapper<>();
        fileQueryWrapper.eq(File::getId, fileId)
                .eq(File::getUserId, userId)
                .isNull(File::getDeletedAt);
        if (fileService.count(fileQueryWrapper) == 0) {
            throw new BusinessException("文件不存在");
        }

        // 检查是否已收藏
        if (isFavorite(fileId, userId)) {
            return true;
        }

        // 添加收藏
        Favorite favorite = new Favorite();
        favorite.setFileId(fileId);
        favorite.setUserId(userId);
        boolean result = this.save(favorite);

        // 更新文件收藏状态
        if (result) {
            LambdaUpdateWrapper<File> fileUpdateWrapper = new LambdaUpdateWrapper<>();
            fileUpdateWrapper.eq(File::getId, fileId)
                    .set(File::getIsFavorite, true);
            fileService.update(fileUpdateWrapper);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeFavorite(Integer fileId, Integer userId) {
        // 检查文件是否存在
        LambdaQueryWrapper<File> fileQueryWrapper = new LambdaQueryWrapper<>();
        fileQueryWrapper.eq(File::getId, fileId)
                .eq(File::getUserId, userId);
        if (fileService.count(fileQueryWrapper) == 0) {
            throw new BusinessException("文件不存在");
        }

        // 删除收藏
        LambdaQueryWrapper<Favorite> favoriteQueryWrapper = new LambdaQueryWrapper<>();
        favoriteQueryWrapper.eq(Favorite::getFileId, fileId)
                .eq(Favorite::getUserId, userId);
        boolean result = this.remove(favoriteQueryWrapper);

        // 更新文件收藏状态
        if (result) {
            LambdaUpdateWrapper<File> fileUpdateWrapper = new LambdaUpdateWrapper<>();
            fileUpdateWrapper.eq(File::getId, fileId)
                    .set(File::getIsFavorite, false);
            fileService.update(fileUpdateWrapper);
        }

        return result;
    }

    @Override
    public PageResult<FileDTO> listFavorites(Integer userId, Integer page, Integer pageSize, String query) {
        // 计算分页参数
        int offset = (page - 1) * pageSize;
        
        // 查询结果
        List<File> files;
        long total;
        
        if (query != null && !query.isEmpty()) {
            // 带搜索条件的查询
            files = baseMapper.selectFavoriteFilesWithQueryDirectSQL(userId, pageSize, offset, query);
            total = baseMapper.countFavoriteFilesWithQuery(userId, query);
        } else {
            // 无搜索条件的查询
            files = baseMapper.selectFavoriteFilesDirectSQL(userId, pageSize, offset);
            total = baseMapper.countFavoriteFiles(userId);
        }

        // 转换为DTO
        List<FileDTO> fileDTOList = files.stream().map(file -> {
            FileDTO fileDTO = new FileDTO();
            BeanUtils.copyProperties(file, fileDTO);
            return fileDTO;
        }).collect(Collectors.toList());

        // 返回分页结果
        return new PageResult<>(total, fileDTOList);
    }


    @Override
    public boolean isFavorite(Integer fileId, Integer userId) {
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getFileId, fileId)
                .eq(Favorite::getUserId, userId);
        return this.count(queryWrapper) > 0;
    }
} 